
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>楼宇管理</title>
    <script src="../js/vue3.js"></script>
    <script src="../js/axios-0.18.0.js"></script>
    <script src="../js/element-plus.js"></script>
    <script src="../js/icons-vue.js"></script>
    <script src="../js/zh-cn.js"></script>
    <!--    <script src="js/axios-interceptor.js"></script>-->
    <link rel="stylesheet" href="../css/index.css"/>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: "Helvetica Neue", Arial, sans-serif;
            background: #f4f6f9;
        }

        .search-container {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            align-items: center;
        }

        .search-container .el-form-item {
            margin: 0;
        }

        .table-container {
            background: #fff;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }

        .pagination-container {
            margin-top: 15px;
            display: flex;
            justify-content: flex-end;
        }

        .table-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
            align-items: center;
        }

        .batch-delete-btn {
            margin-left: 10px;
        }
        .name-search {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .table-container {
            display: flex;
            flex-direction: column;
            height: calc(100vh - 220px); /* 动态计算高度（原样式中已有padding/margin，这里需要加大减去的值） */
            min-height: 300px; /* 最小高度保障 */
        }
        .el-table {
            flex: 1;
            overflow: auto;
            margin-bottom: 10px; /* 与分页控件的间距 */
        }
        .el-table__body-wrapper {
            scrollbar-width: thin; /* 更细的滚动条（Firefox） */
        }
        /* 滚动条样式（可选） */
        .el-table__body-wrapper::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 表格 -->
    <div class="table-container">
        <!-- 表格顶部操作按钮 -->
        <div class="table-header">
            <div>
                <el-button type="success" @click="addNewBuilding">新增楼宇</el-button>
                <el-button type="danger" @click="handleBatchDelete"  >批量删除</el-button>
            </div>
        </div>

        <el-table
                :data="tableData"
                border
                stripe
                style="width: 100%"
                @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="buildingId" label="楼宇编号" width="120"></el-table-column>
            <!-- ========== 修改的列：楼宇名称（添加搜索框） ========== -->
            <el-table-column prop="buildingName" label="楼宇名称" width="200">
                <template #header>
                    <div class="name-search">
                        <span>楼宇名称</span>
                        <el-input
                                v-model="search"
                                placeholder="搜索名称"
                                size="small"
                                @input="getAllBuilding">
                        </el-input>
                    </div>
                </template>
            </el-table-column>
            <!-- =============================================== -->

            <el-table-column prop="location" label="单元号" width="120"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="filteredTotal"
                    :page-sizes="[5, 10, 20, 30]"
                    v-model:page-size="pageSize"
                    v-model:current-page="currentPage"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"></el-pagination>
        </div>
    </div>
    <el-dialog
            v-model="dialogVisible"
            title="楼宇信息"
            width="500px"
            @close="handleClose">
        <!-- 表单内容 -->
        <el-form :model="form" :rules="rules" ref="buildingFormRef" label-width="80px">
            <el-form-item label="楼宇名称" prop="buildingName">
                <el-input v-model="form.buildingName" placeholder="请输入楼宇名称"></el-input>
            </el-form-item>
            <el-form-item label="单元号" prop="location">
                <el-input v-model="form.location" placeholder="请输入单元号"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input
                        v-model="form.remark"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入备注信息"></el-input>
            </el-form-item>
        </el-form>

        <!-- 弹窗底部按钮 -->
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">保存</el-button>
        </span>
        </template>
    </el-dialog>
</div>
<script>
    const {createApp, ref,computed, onMounted, onUpdated} = Vue;
    const {ElMessage, ElMessageBox} = ElementPlus;
    const app = createApp({

        setup() {

            // 原始数据
            const search = ref("")

            const tableData = ref([]);
            const total = ref(0);
            const pageSize = ref(5);
            const currentPage = ref(1);

            // 弹窗显示状态
            const dialogVisible = ref(false)
            // 表单数据
            const form = ref({});

            const buildingFormRef = ref(null)
            const rules = ref({
                buildingName: [
                    {required: true, message: '楼宇名称不能为空', trigger: 'blur'},
                ],
                location: [
                    {required: true, message: '单元号不能为空', trigger: 'blur'},
                ],
            })

            const refreshData = (msg)=>{
                ElMessage.success(msg);
                form.value = {}
                dialogVisible.value = false
                getAllBuilding()
            };
            const addNewBuilding =()=>{
                dialogVisible.value = true;
                form.value = {}
            }
            //新增楼宇
            const handleConfirm = () => {

                if(buildingFormRef.value.validate(valid => {
                    if (valid) {
                        if (form.value.buildingId) {
                            axios.put("/building", form.value).then(resp => {
                                refreshData(resp.data.msg);
                            }).catch(error => {
                                ElMessage.error(error.response.data.msg);
                            })
                        } else {
                            axios.post("/building", form.value).then(resp => {
                                refreshData(resp.data.msg)
                            }).catch(error => {
                                ElMessage.error(error.response.data.msg);
                            })
                        }
                    }
                }));
            }

            // 弹窗关闭事件
            const handleClose = () => {
                // 重置表单
               dialogVisible.value = false
            }

            const filteredTotal = computed(() => total.value);


            const getAllBuilding = () => {
                    let url = search.value
                        ? `/building/${currentPage.value}/${pageSize.value}/${search.value}`
                        : `/building/${currentPage.value}/${pageSize.value}`;
                    axios.get(url)
                        .then(resp => {
                            console.log("后端返回数据",resp.data);
                            tableData.value = resp.data.data.data;
                            total.value = resp.data.data.total;
                })
            };

            // 处理搜索
            const handleSearch = () => {
                currentPage.value = 1;
                getAllBuilding();
            };

            const ids =ref([]);
            // 处理多选
            const handleSelectionChange = (val) => {
                ids.value = val.map(item =>item.buildingId)
            };
            // 处理批量删除
            const handleBatchDelete = () => {
                if (ids.value.length > 0) {
                    axios.post('/building/deleteBuildings',ids.value)
                    .then(resp => {
                        refreshData(resp.data.msg)
                    }).catch(error=>{
                        ElMessage.error(error.response.data.msg)
                    })
                }

            };

            // 处理编辑
            const handleEdit = (row) => {
                    axios.get(`/building/${row.buildingId}`).then(resp => {
                    form.value = resp.data.data;
                    dialogVisible.value = true
                    }).catch(error=>{
                        ElMessage.error(error.response.data,msg)
                    })
            };

            // 处理删除
            const handleDelete = (row) => {
                ElMessageBox.confirm(`确定要删除楼宇 ${row.buildingName} 吗?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleteBuilding(row.buildingId)
                }).catch(() => {
                    ElMessage.info('已取消删除');
                });
            };
            const deleteBuilding = (id) => {
                axios.delete(`/building/${id}`).then(resp => {
                    ElMessage.success(resp.data.msg);
                    getAllBuilding();
                }).catch(() => {
                    ElMessage.error(error.response.data.msg)
                })

            }

            // 处理分页大小变化
            const handleSizeChange = (val) => {
                pageSize.value = val;
                currentPage.value = 1;
                getAllBuilding();
            };

            // 处理页码变化
            const handlePageChange = (val) => {
                currentPage.value = val;
                getAllBuilding();
            };

            onMounted(() => {
                console.log("已挂载");
                getAllBuilding();
            })

            return {
                search,tableData,total,
                pageSize,filteredTotal,rules,buildingFormRef,
                currentPage,form,handleConfirm,handleClose,
                handleSearch,dialogVisible,addNewBuilding,
                handleBatchDelete,
                handleEdit,
                handleDelete,deleteBuilding,
                handleSizeChange,
                handlePageChange,
                ids,handleSelectionChange,
                getAllBuilding
            };
        }
    });
    app.use(ElementPlus, {
        locale: ElementPlusLocaleZhCn
    });
    // 注册 Element Plus 图标
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component);
    }
    app.mount("#app");
</script>

</body>
</html>